# Title     : TODO
# Objective : TODO
# Created by: Administrator
# Created on: 2019/6/18

library(ropls)
library(plyr)
library(ggplot2)
library(dplyr)
library(tidyr)
library(tibble)
library(magrittr)
library(optparse)

createWhenNoExist <- function(f){
    ! dir.exists(f) && dir.create(f)
}

option_list <- list(
make_option("--g", default = "SampleInfo.csv", type = "character", help = "sample group file"),
make_option("--sc", default = "sample_color.txt", type = "character", help = "sample color file")
)
opt <- parse_args(OptionParser(option_list = option_list))

options(digits = 3)

sampleColDf <- read.csv(opt$sc, header = T, stringsAsFactors = F, comment.char = "") %>%
select(c("ClassNote", "col"))
sampleCols <- sampleColDf %>%
deframe()

parent <- paste0("./")
createWhenNoExist(parent)
modeFileName <- paste0(parent, "/OPLSDA_R2X_R2Y_Q2.csv")
pdfFileName <- paste0(parent, "/OPLSDA_R2X_R2Y_Q2.pdf")
modelDf <- read.csv(modeFileName, header = T, stringsAsFactors = F, comment.char = "", row.names = 1)

plotData <- modelDf %>%
    rownames_to_column("poName") %>%
    filter(poName %in% c("P1", "O1")) %>%
    select(c("poName", "R2X", "R2Y", "Q2")) %>%
    gather("group", "value", - poName) %>%
    mutate(group = factor(group, levels = c("R2X", "R2Y", "Q2"))) %>%
    mutate(poName = factor(poName, levels = c("P1", "O1")))

head(plotData)

p <- ggplot(plotData, mapping = aes(x = poName, y = value, fill = group, label = value)) +
    xlab("") +
    ylab("") +
    theme_bw(base_size = 8.8, base_family = "Times") +
    theme(axis.text.x = element_text(size = 9, vjust = 0.5),
    axis.text.y = element_text(size = 8.8), legend.position = 'right',
    axis.title.y = element_text(size = 12), legend.margin = margin(t = 0.3, b = 0.1, unit = 'cm'),
    legend.text = element_text(size = 9), axis.title.x = element_text(size = 12),
    panel.grid.major = element_blank(), panel.grid.minor = element_blank(),
    ) +
    geom_bar(stat = "identity", position = position_dodge()) +
    geom_text(size = 3.5, family = "Times", vjust = - 0.3, position = position_dodge(0.9)) +
    scale_colour_manual("", values = sampleCols) +
    scale_fill_manual("", values = c("#ADD8E6", "#FFE4E1", "#E6E6FA"))
ggsave(limitsize = FALSE,pdfFileName, p, width = 7, height = 5)




